package com.example.config.shiro;

import com.example.pojo.Audience;
import com.example.pojo.User;
import com.example.pojo.user.UserRole;
import com.example.service.UserRoleService;
import com.example.service.UserService;
import com.example.utils.JwtTokenUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class UserRealm extends AuthorizingRealm {
    // 授权
    @Autowired
    UserService userService;
    @Autowired
    Audience audience;
    @Autowired
    UserRoleService userRoleService;

    /**
     * 大坑！，必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进行授权");

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        User user = (User) SecurityUtils.getSubject().getPrincipal();

        if (user.getPermissions() != null) {
            for (String per : user.getPermissions()) {
                authorizationInfo.addStringPermission(per);
            }
        }
        if (user.getRoles() != null) {
            user.getRoles().forEach((String role) -> {
                authorizationInfo.addRole(role);
            });
        }
        return authorizationInfo;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        String userToken = (String) authenticationToken.getCredentials();
        String username = JwtTokenUtil.getUsername(userToken, audience.getBase64Secret());
        if (username == null) {
            throw new AuthenticationException(" token错误，请重新登入！");
        }
        User userBean = userService.get(username);
        if (userBean == null) {
            throw new AccountException("账号不存在!");
        }
        if (!userBean.getPassword().equals(JwtTokenUtil.getPassword(userToken, audience.getBase64Secret()))) {
            throw new CredentialsException("密码错误!");
        }
        User user_permission = userService.getUserPermission(userBean);
        List<UserRole> roles = userRoleService.selectByPrimaryKey(userBean.getUuid());
        if (user_permission != null) {
            if (!user_permission.getPermissions().isEmpty()) {
                userBean.setPermissions(user_permission.getPermissions());
            }
        }
        List<String> r = new ArrayList<>();
        if (roles != null) {
            roles.forEach((UserRole u) -> {
                r.add(u.getRole());
            });
            userBean.setRoles(r);
        }
        return new SimpleAuthenticationInfo(userBean, userToken, getName());
    }
}
